package dao;

import entity.Director;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
import javax.persistence.*;

/**
 *
 * @author Javier
 */
public class DirectorDao {
    private EntityManagerFactory emf = null;
    private EntityManager em = null;
    private EntityTransaction et = null;
    
    public boolean persistDirector(Director director){    
        boolean result=false;
        try{
        emf = Persistence.createEntityManagerFactory("GRLUPUPU");
        em = emf.createEntityManager();
        et = em.getTransaction();
        et.begin();
        
        director = em.merge(director);
        em.flush();
        em.persist(director);
        
        et.commit(); 
        result=true;
        }catch(Exception e){
            if (em != null && et != null){
                et.rollback();
            }
        }finally{
            if (em != null){
                em.clear();
                em.close();
            }
            return result;
        }
    }
    
    public List<Director> findAllDirectorsByNameAndLastName (String directorName, String directorLastname){
        List<Director> directors = null;
        try{
        emf = Persistence.createEntityManagerFactory("GRLUPUPU");
        em = emf.createEntityManager();
        et = em.getTransaction();
        et.begin();        
        Query q = em.createQuery("Director.findByName",Director.class);
        q.setParameter("dirName", directorName);
        q.setParameter("dirLastname", directorLastname);
        directors = q.getResultList();        
        et.commit(); 
        }catch(Exception e){
            if (em != null && et != null){
                et.rollback();
            }
        }finally{
            if (em != null){
                em.clear();
                em.close();
            }
            return directors;
        }
    }
    
        public List<Director> findAllDirectorsByName(String wordsToLookFor){
            //Returned value
            List<Director> directors = new ArrayList();
            // Set which contains the movie's id only once
            HashSet<Integer> directorsId = new HashSet();

            //Divide the string into its tokens.
            //String wordsToLookFor = "palabras para la busqueda de peliculas";
            StringTokenizer tokens=new StringTokenizer(wordsToLookFor, " ");
            ArrayList<String> words = new ArrayList();
            int j = 0;
            while (tokens.hasMoreTokens()){
                String next=tokens.nextToken();
                words.add(next);
                //System.out.println(words.get(j).toString());
                j++;
            }

            for( int i = 0; i < words.size(); i++){
                // List of movies in each iteration.
                List<Director> d;

                try{
                        emf = Persistence.createEntityManagerFactory("GRLUPUPU");
                        em = emf.createEntityManager();
                        et = em.getTransaction();
                        et.begin();

                        String qlString = "SELECT d FROM Director AS d WHERE d.dirName LIKE :code OR d.dirLastname LIKE :code"; 
                        Query q = em.createQuery(qlString, Director.class);
                        q.setParameter("code", "%"+words.get(i).toString()+"%");
                        d = q.getResultList();
                        //Adding the Id's only once
                        for ( int k = 0; k < d.size(); k++){
                            directorsId.add(new Integer (d.get(k).getIdDirector()));
                        }

                        et.commit();    
                    }catch(Exception e){
                        if (em != null && et != null){
                            et.rollback();
                        }
                    }finally{
                        if (em != null){
                            em.clear();
                            em.close();
                        }   
                    }
                        Object[] result = directorsId.toArray();
                        for (int l = 0; l < directorsId.size(); l++){
                            directors.add((Director)findDirectorById((Integer)result[l]));
                        }
            }
            return directors;
    }
    
    public Director findDirectorById(Integer id){
        Director director = null;
        try{
            emf = Persistence.createEntityManagerFactory("GRLUPUPU");
            em = emf.createEntityManager();
            et = em.getTransaction();
            et.begin();

            Query q = em.createNamedQuery("Director.findByIdDirector", Director.class);
            q.setParameter("idDirector", id);
            director = (Director) q.getSingleResult();
            et.commit();

        }catch(Exception e){
            if (em != null && et != null){
                et.rollback();
            }
        }finally{
            if (em != null){
                em.clear();
                em.close();
            }

        }     
        return director;
    }
        
    
    
    public boolean deleteDirector(Director director) {
        boolean result = false;
        try {
            emf = Persistence.createEntityManagerFactory("GRLUPUPU");
            em = emf.createEntityManager();
            et = em.getTransaction();
            et.begin();        
            em.remove(director);
            em.getTransaction().commit();
            result = true;
        } catch (Exception e) {
            if (em != null && et != null){
                et.rollback();
            }
        } finally {
            if (em != null){
                em.clear();
                em.close();
            }
            return result;
        }
    }
}
